package com.guaju.yueshangLife.fragment.home;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.example.xrecyclerview.XRecyclerView;
import com.guaju.yueshangLife.BR;
import com.guaju.yueshangLife.R;
import com.guaju.yueshangLife.adapter.CommonRecyclerViewAdapter;
import com.guaju.yueshangLife.base.BaseFragment;
import com.guaju.yueshangLife.bean.Goods;
import com.guaju.yueshangLife.bean.GoodsListTotal;
import com.guaju.yueshangLife.bean.HomeTotal;
import com.guaju.yueshangLife.databinding.FragmentTotalgoodsBinding;
import com.guaju.yueshangLife.fragment.HomeFragment;
import com.guaju.yueshangLife.net.ApiEntity;
import com.guaju.yueshangLife.utils.CommonUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by guaju on 2018/10/9.
 */

public class TotalGoodsFragment extends BaseFragment<FragmentTotalgoodsBinding> {
    private static final String TYPE = "TotalGoodsFragment";
    private static final String TAB_ID = "tab_id";
    private boolean mIsPrepared;
    private boolean mIsFirst = true;
    private int page = 1;

    private boolean isSalesUp = false;//箭头默认向下
    private boolean isNewUp = true;//箭头默认向上
    private boolean isPriceUp = true;//箭头默认向上

    private String currentSort = "";
    private String currentIsIncrease = "";


    // 开始请求的角标
    private int mStart = 0;
    // 一次请求的数量
    private int mCount = 18;
    //
    private GridLayoutManager mLayoutManager;


    ArrayList goodsList = new ArrayList<>();
    private CommonRecyclerViewAdapter<Goods> totalGoodsAdapter;
    private String tab_id;
    private int total;

    @Override
    public int setContent() {
        return R.layout.fragment_totalgoods;
    }

    public static TotalGoodsFragment newInstance(String param) {
        TotalGoodsFragment fragment = new TotalGoodsFragment();
        Bundle args = new Bundle();
        args.putString(TYPE, param);
        fragment.setArguments(args);
        return fragment;
    }

    public static TotalGoodsFragment newInstance(HomeFragment.TabBean tabBean) {
        TotalGoodsFragment fragment = new TotalGoodsFragment();
        Bundle args = new Bundle();
        args.putString(TYPE, tabBean.getTabName());
        args.putString(TAB_ID, tabBean.getTabId());
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 准备就绪
        mIsPrepared = true;
        loadData();
        showContentView();
        bindingView.srlTotalGoods.setColorSchemeColors(CommonUtils.getColor(R.color.colorTheme));
        bindingView.srlTotalGoods.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                bindingView.srlTotalGoods.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        page=1;
                        loadData();
                    }
                }, 1000);

            }
        });
        mLayoutManager = new GridLayoutManager(getActivity(), 2);
        bindingView.recyclerview.setLayoutManager(mLayoutManager);
        //recyclerview
        scrollRecycleView();
        setListener();
        bindingView.sortNewIconUpDown.setVisibility(View.INVISIBLE);
        bindingView.sortSalesIconUpDown.setVisibility(View.INVISIBLE);
        bindingView.sortPriceIconUpDown.setVisibility(View.INVISIBLE);
        bindingView.sortNormal.setChecked(true);
    }

    private void setListener() {
        View.OnClickListener saleSortClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentSort = "sales";
                checkRelax();
                bindingView.sortSale.setChecked(true);
                bindingView.sortSalesIconUpDown.setVisibility(View.VISIBLE);
                if (isSalesUp) {
                    isSalesUp = false;
                    bindingView.sortSalesIconUpDown.setChecked(false);
                    requestData("sales", false);
                } else {
                    isSalesUp = true;
                    bindingView.sortSalesIconUpDown.setChecked(true);
                    requestData("sales", true);
                }
                currentIsIncrease = isSalesUp ? "asc" : "desc";
            }
        };


        View.OnClickListener priceSortClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentSort = "price";
                checkRelax();
                bindingView.sortPrice.setChecked(true);
                bindingView.sortPriceIconUpDown.setVisibility(View.VISIBLE);
                if (isPriceUp) {
                    isPriceUp = false;
                    bindingView.sortPriceIconUpDown.setChecked(false);
                    requestData("price", false);
                } else {
                    isPriceUp = true;
                    bindingView.sortPriceIconUpDown.setChecked(true);
                    requestData("price", true);
                }
                currentIsIncrease = isPriceUp ? "asc" : "desc";
            }
        };

        View.OnClickListener newSortClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentSort = "new";
                checkRelax();
                bindingView.sortNew.setChecked(true);
                bindingView.sortNewIconUpDown.setVisibility(View.VISIBLE);
                if (isNewUp) {
                    isNewUp = false;
                    bindingView.sortNewIconUpDown.setChecked(false);
                    requestData("publish", false);
                } else {
                    isNewUp = true;
                    bindingView.sortNewIconUpDown.setChecked(true);
                    requestData("publish", true);
                }
                currentIsIncrease = isNewUp ? "asc" : "desc";
            }
        };
        bindingView.llSortSales.setOnClickListener(saleSortClickListener);
        bindingView.llSortPrice.setOnClickListener(priceSortClickListener);
        bindingView.llSortNew.setOnClickListener(newSortClickListener);
        bindingView.sortNew.setOnClickListener(newSortClickListener);
        bindingView.sortSale.setOnClickListener(saleSortClickListener);
        bindingView.sortPrice.setOnClickListener(priceSortClickListener);
    }

    private void checkRelax() {
        bindingView.sortNew.setChecked(false);
        bindingView.sortPrice.setChecked(false);
        bindingView.sortSale.setChecked(false);
        bindingView.sortNormal.setChecked(false);

        bindingView.sortNewIconUpDown.setVisibility(View.INVISIBLE);
        bindingView.sortPriceIconUpDown.setVisibility(View.INVISIBLE);
        bindingView.sortSalesIconUpDown.setVisibility(View.INVISIBLE);
    }

    private void requestData(String sort, boolean isIncrease) {
        page = 1;
        goodsList.clear();
        ApiEntity.goods(page, tab_id, sort, isIncrease ? "asc" : "desc", new Callback<GoodsListTotal>() {
            @Override
            public void onResponse(Call<GoodsListTotal> call, Response<GoodsListTotal> response) {
                if (response.isSuccessful()) {
                    GoodsListTotal goodsListTotal = response.body();
                    if (goodsListTotal != null) {
                        GoodsListTotal.DataBean data = goodsListTotal.getData();
                        total = data.getTotal();
                        List<GoodsListTotal.DataBean.ResultBean> result = data.getResult();

                        if (result == null || result.isEmpty()) {
                            showEmpty();
                            if (totalGoodsAdapter != null)
                                totalGoodsAdapter.updateLoadStatus(totalGoodsAdapter.LOAD_END);
                        } else {
                            for (GoodsListTotal.DataBean.ResultBean productsBean : result) {
                                goodsList.add(new Goods(productsBean.getCover().getHost() + productsBean.getCover().getPath(),
                                        productsBean.getName(),
                                        productsBean.getTags(),
                                        productsBean.getPrice().getCurrent() + "",
                                        productsBean.getId() + ""));
                            }
                            loadCustomData(total);
                        }
                    } else {
                        showEmpty();
                    }

                } else {
                    showEmpty();
                }
            }

            @Override
            public void onFailure(Call<GoodsListTotal> call, Throwable t) {
                showEmpty();
            }
        });
    }

    @Override
    protected void loadData() {
        if (!mIsPrepared || !mIsVisible || !mIsFirst) {
            return;
        }
        mIsFirst = false;
        Bundle arguments = getArguments();
        tab_id = arguments.getString(TAB_ID);
        ApiEntity.goods(page, tab_id, new Callback<GoodsListTotal>() {
            @Override
            public void onResponse(Call<GoodsListTotal> call, Response<GoodsListTotal> response) {
                if (bindingView.srlTotalGoods.isRefreshing()){
                    bindingView.srlTotalGoods.setRefreshing(false);
                }
                if (response.isSuccessful()) {
                    GoodsListTotal goodsListTotal = response.body();
                    if (goodsListTotal != null) {
                        GoodsListTotal.DataBean data = goodsListTotal.getData();
                        total = data.getTotal();
                        List<GoodsListTotal.DataBean.ResultBean> result = data.getResult();

                        if (result == null || result.isEmpty()) {
                            if (1 == page) {
                                showEmpty();
                            }
                            loadCustomData(total);
                        } else {
                            for (GoodsListTotal.DataBean.ResultBean productsBean : result) {
                                goodsList.add(new Goods(productsBean.getCover().getHost() + productsBean.getCover().getPath(),
                                        productsBean.getName(),
                                        productsBean.getTags(),
                                        productsBean.getPrice().getCurrent() + "",
                                        productsBean.getId() + ""));
                            }
                            loadCustomData(total);
                        }
                    } else {
                        if (1 == page) {
                            showEmpty();
                        }
                    }

                }else{
                    showEmpty();
                }
            }

            @Override
            public void onFailure(Call<GoodsListTotal> call, Throwable t) {
                if (bindingView.srlTotalGoods.isRefreshing()){
                    bindingView.srlTotalGoods.setRefreshing(false);
                }
                if (1 == page) {
                    showEmpty();
                }
            }
        });
    }

    private void loadCustomData(int size) {
        if (totalGoodsAdapter == null) {
            totalGoodsAdapter = new CommonRecyclerViewAdapter<Goods>(getActivity(), getLayoutInflater(), R.layout.item_goods, BR.goods, goodsList);
            bindingView.recyclerview.setAdapter(totalGoodsAdapter);
        } else {
            if (size < 10) {
                if (1 == page) {
                    totalGoodsAdapter.updateLoadStatus(totalGoodsAdapter.LOAD_LESS);
                } else {
                    totalGoodsAdapter.updateLoadStatus(totalGoodsAdapter.LOAD_END);
                }
            } else {
                totalGoodsAdapter.updateLoadStatus(totalGoodsAdapter.LOAD_PULL_TO);
            }
        }
        if (bindingView.srlTotalGoods.isRefreshing()) {
            bindingView.srlTotalGoods.setRefreshing(false);
        }
    }


    //计算recyclerview滑动，展示下拉刷新，上拉加载
    public void scrollRecycleView() {
        bindingView.recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

                    /**StaggeredGridLayoutManager*/
//                    int[] into = new int[(mLayoutManager).getSpanCount()];
//                    lastVisibleItem = findMax(mLayoutManager.findLastVisibleItemPositions(into));

                    if (totalGoodsAdapter == null) {
                        return;
                    }
                    if (mLayoutManager.getItemCount() == 0) {
                        totalGoodsAdapter.updateLoadStatus(totalGoodsAdapter.LOAD_NONE);
                        return;

                    }
                    if (lastVisibleItem + 1 == mLayoutManager.getItemCount()
                            && totalGoodsAdapter.getLoadStatus() != totalGoodsAdapter.LOAD_MORE) {
//                        mBookAdapter.updateLoadStatus(BookAdapter.LOAD_PULL_TO);
                        // isLoadMore = true;
                        totalGoodsAdapter.updateLoadStatus(totalGoodsAdapter.LOAD_MORE);
                        page++;
                    }

                    if (TextUtils.isEmpty(currentSort)) {
                        ApiEntity.goods(page, tab_id, new Callback<GoodsListTotal>() {
                            @Override
                            public void onResponse(Call<GoodsListTotal> call, Response<GoodsListTotal> response) {
                                if (response.isSuccessful()) {
                                    GoodsListTotal goodsListTotal = response.body();
                                    if (goodsListTotal != null) {
                                        GoodsListTotal.DataBean data = goodsListTotal.getData();
                                        total = data.getTotal();
                                        List<GoodsListTotal.DataBean.ResultBean> result = data.getResult();
                                        //说明刷新到了最底部
                                        if (result == null || result.isEmpty()) {
                                            totalGoodsAdapter.updateLoadStatus(totalGoodsAdapter.LOAD_END);
                                        } else {
                                            for (GoodsListTotal.DataBean.ResultBean productsBean : result) {
                                                goodsList.add(new Goods(productsBean.getCover().getHost() + productsBean.getCover().getPath(),
                                                        productsBean.getName(),
                                                        productsBean.getTags(),
                                                        productsBean.getPrice().getCurrent() + "",
                                                        productsBean.getId() + ""));
                                            }
                                            loadCustomData(total);
                                        }
                                    }

                                }
                            }

                            @Override
                            public void onFailure(Call<GoodsListTotal> call, Throwable t) {

                            }
                        });
                    } else {
                        ApiEntity.goods(page, tab_id, currentSort, currentIsIncrease, new Callback<GoodsListTotal>() {
                            @Override
                            public void onResponse(Call<GoodsListTotal> call, Response<GoodsListTotal> response) {
                                if (response.isSuccessful()) {
                                    GoodsListTotal goodsListTotal = response.body();
                                    if (goodsListTotal != null) {
                                        GoodsListTotal.DataBean data = goodsListTotal.getData();
                                        total = data.getTotal();
                                        List<GoodsListTotal.DataBean.ResultBean> result = data.getResult();
                                        //说明刷新到了最底部
                                        if (result == null || result.isEmpty()) {
                                            totalGoodsAdapter.updateLoadStatus(totalGoodsAdapter.LOAD_END);
                                        } else {
                                            for (GoodsListTotal.DataBean.ResultBean productsBean : result) {
                                                goodsList.add(new Goods(productsBean.getCover().getHost() + productsBean.getCover().getPath(),
                                                        productsBean.getName(),
                                                        productsBean.getTags(),
                                                        productsBean.getPrice().getCurrent() + "",
                                                        productsBean.getId() + ""));
                                            }
                                            loadCustomData(total);
                                        }
                                    }

                                }
                            }

                            @Override
                            public void onFailure(Call<GoodsListTotal> call, Throwable t) {

                            }
                        });
                    }
                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

                /**StaggeredGridLayoutManager*/
//                int[] into = new int[(mLayoutManager).getSpanCount()];
//                lastVisibleItem = findMax(mLayoutManager.findLastVisibleItemPositions(into));
            }
        });
    }

    private void showEmpty() {
        bindingView.emptyview.getRoot().setVisibility(View.VISIBLE);
        TextView retryButton = bindingView.emptyview.getRoot().findViewById(R.id.tv_goIndex);
        retryButton.setText("点击重试");
        TextView showText = bindingView.emptyview.getRoot().findViewById(R.id.tv_order_empty);
        showText.setText("暂无数据,请稍后重试");
        retryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bindingView.emptyview.getRoot().setVisibility(View.GONE);
                loadData();
            }
        });
    }
}